package com.krtech.wecard.module.ramble.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.krtech.wecard.framework.utils.LoginUtil;
import com.krtech.wecard.module.ramble.entity.RambleDrawChance;
import com.krtech.wecard.module.ramble.entity.RambleShareQrcode;
import com.krtech.wecard.module.ramble.service.RambleDrawChanceService;
import com.krtech.wecard.module.sys.entity.SysUser;
import com.krtech.wecard.utils.DfsUtil;
import com.krtech.wecard.utils.WxUtil;
import com.krtech.wecard.utils.qrcode.QRCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.krtech.wecard.module.ramble.entity.RambleHexiaoLog;
import com.krtech.wecard.module.ramble.mapper.RambleHexiaoLogMapper;
import com.krtech.wecard.module.ramble.service.RambleHexiaoLogService;

@Service
public class RambleHexiaoLogServiceImpl extends ServiceImpl<RambleHexiaoLogMapper, RambleHexiaoLog> implements RambleHexiaoLogService {

    @Autowired
    private WxUtil wxUtil;

    private static String URL = "https://seemax.cc";

    @Autowired
    private RambleDrawChanceService drawChanceService;

    @Override
    public String getHexiaoCode(Integer id) {
        SysUser userInfo = LoginUtil.getUserInfo();

        //如果当前已经有了就不用生成了
        RambleDrawChance drawChance = drawChanceService.getById(id);
        if (drawChance.getHexiaoUrl() != null) {
            return drawChance.getHexiaoUrl();
        }

//        String accessToken = wxUtil.getAccessToken();
//
//        HttpRequest post = HttpUtil.createPost("https://api.weixin.qq.com/wxa/getwxacode?access_token=" + accessToken);
//
        String code = IdUtil.simpleUUID();
//
//        HashMap<Object, Object> map = new HashMap<>();
//        //todo 路由得后期改 或者还能优化 优化到扫码直接给一个code，然后直接换信息
//        map.put("path", "/pages/index/index?hexiao=" + code);
//
//        post.body(JSONUtil.toJsonStr(map));
//        HttpResponse execute = post.execute();
//
//        File file = FileUtil.writeBytes(execute.bodyBytes(), "/tmp/generateHexiaoCode/" + code + ".jpg");
//
//        DfsUtil dfsUtil = new DfsUtil();
//        DfsUtil.DfsFile upload = dfsUtil.upload(file);

        DfsUtil.DfsFile upload = QRCodeUtil.encodeUpLoad("UTF-8", code, 300, 300, "PNG", "/tmp/" + code + ".png");

        //将地址保存下来
        String url = URL + upload.getSrc();

        //讲code和url保存到数据库
        drawChance.setHexiaoCode(code);
        drawChance.setHexiaoUrl(url);
        drawChanceService.updateById(drawChance);

        return url;
    }
}


